package com.example.xlmkotlinwanandroid.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.xlmkotlinwanandroid.R
import com.example.xlmkotlinwanandroid.base.BaseFragment
import com.example.xlmkotlinwanandroid.databinding.FragmentProjectBinding
import com.example.xlmkotlinwanandroid.model.viewmodel.ProjectViewModel
import com.example.xlmkotlinwanandroid.ui.adapter.ProjectPagerAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

/**
 * 项目fragment
 */
class ProjectFragment : BaseFragment() {

    private lateinit var projectBinding: FragmentProjectBinding
    private val projectViewModel: ProjectViewModel by viewModels<ProjectViewModel>()

    //将adapter改为局部变量
    //private val projectAdapter by lazy { activity?.let { ProjectAdapter(it) } }
    private var fragments = ArrayList<Fragment>()
    private var titles: ArrayList<String> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return initView(inflater, container)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
    }


    private fun initData() {


    }

    private fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): View? {
        projectBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_project, container, false);
        //设置tablayout可以滑动
        projectBinding.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        val projectAdapter =
            activity?.let { ProjectPagerAdapter(it, fragments) }
        projectBinding.viewPager.adapter = projectAdapter
        //绑定tabLayout和viewPager
        TabLayoutMediator(
            projectBinding.tabLayout, projectBinding.viewPager, true, true
        ) { tab, position ->
            tab.text = titles[position]
        }.attach()
        //因为adapter是局部变量了，所以需要在此处监听变化
        projectViewModel.getProjectCategory().observe(viewLifecycleOwner, {
            val categoryList = it
            if (fragments.size > 0) {
                fragments.clear()
            }
            for (i in 0 until categoryList.size - 1) {
                val categoryName = categoryList[i].name
                if (categoryName != null) {
                    titles.add(categoryName)
                    fragments.add(TabFragment(categoryList[i].id))
                }
            }
            projectAdapter?.notifyDataSetChanged()
        })

        return projectBinding.root
    }


}